/**
 * @copyright Copyright (c) 2025 
 * CSG Digital Grid Technology (Guangdong) Co., Ltd.
 * @author xxxcsg
 */

#include "Utility.h"

#include "../3rd/mongoose.h"
#include "../3rd/cJSON.h"

void to_hex(char* s, int len, char* hex_str)
{
    static char hex_table[] = { '0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f' };
    
    while (len--)
    {
        *(hex_str + 2 * len + 1) = hex_table[*(s + len) & 0x0f];
        *(hex_str + 2 * len) = hex_table[*(s + len) >> 4 & 0x0f];
    }

   // 可以采用 mongoose 的实现 
    //mg_snprintf(hex_str, DIGEST_MAX_LEN * 2 + 1, "%M", mg_print_hex, len, s);
}


int hash_file(const char* filepath, char* hash_hex)
{
    // int ret = 0;
    if (filepath == NULL || strlen(filepath) == 0)
    {
        return -1;
    }

    FILE* fp = NULL;
    fp = fopen(filepath, "rb");
    if (fp == NULL) {
        printf("%s open failed:%d\n", filepath,errno);
        return -1;
    }

    mg_sha256_ctx sha256_ctx;
    mg_sha256_init(&sha256_ctx);

    char buffer[BUFFER_LEN] = { 0 };
    size_t count = 0;
    while (!feof(fp) && !ferror(fp))
    {
        count = fread(buffer, sizeof(char), BUFFER_LEN, fp);
        mg_sha256_update(&sha256_ctx, (unsigned char*)buffer, count);
    }

    char digest[DIGEST_MAX_LEN] = { 0 };
    mg_sha256_final((unsigned char*)digest, &sha256_ctx);
    to_hex(digest, DIGEST_MAX_LEN, hash_hex);

    return 0;
}

int read_file(const char* filepath, char** data)
{
    // int ret = 0;
    char* buf = NULL;
    if (filepath == NULL || strlen(filepath) == 0)
    {
        return -1;
    }

    FILE* fp = NULL;
    long file_length = 0;

    fp = fopen(filepath, "rb");
    if (fp == NULL) {
        printf("%s open failed.\n", filepath);
        return -1;
    }

    fseek(fp, 0, SEEK_END);
    file_length = ftell(fp);
    fseek(fp, 0, SEEK_SET);

    buf = (char*)malloc(file_length + 1);
    if (buf == NULL)
    {
        return -1;
    }
    memset(buf, 0, file_length + 1);
    fread(buf, 1, file_length, fp);
    fclose(fp);

    *data = buf;
    return 0;
}